﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using WebApiV2.Data;
using WebApiV2.Data.Model;

namespace WebApiV2.Domain
{
    //实现接口
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {

        //数据库上下文
        private readonly Admain1000DbContext db;

        //依赖注入
        public EfRespository(Admain1000DbContext dbContext)
        {
            db = dbContext;
        }


        private DbSet<T> _entity;

        //判断_entity是否为空值
        protected DbSet<T> Entity
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }

        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }


     
        //根据id删除
        public void Deleted(int id)
        {
            var row = Table.Where(x => x.id == id).FirstOrDefault();
           // Deleted(row);
        }
        //多条数据删除
        public void DeletedBulk(T entity)
        {
           Entity.Remove(entity);
            db.SaveChanges();

        }

        //查询
        public T GetByid(int id)
        {
           return Entity.Where(x => x.id == id).FirstOrDefault();

        }
        //添加
        public void insert(T entity)
        {
            Entity.Add(entity);
            db.SaveChanges();
        }
        //多条数据添加
        public void insertBulk(IEnumerable<T> list)
        {
            Entity.AddRange(list);
            db.SaveChanges();
        }
        //更新
        public void Update(T entity)
        {
            Entity.Update(entity);
            db.SaveChanges();
        }

        public void Delete(IEnumerable<T> entities)
        {
            Entity.RemoveRange(entities);
            db.SaveChanges();
        }

        public T GetById(int id)
        {
            return Entity.Where(x => x.id == id).FirstOrDefault();
        }

       
    }
}
